Imports Clo = Enhancements.Core.Logging
Imports Ere = Enhancements.Basic.RegularExpressions
Imports Gen = System.Collections.Generic
Imports Glo = System.Globalization
Imports Iou = System.IO
Imports Ref = System.Reflection
Imports Reg = System.Text.RegularExpressions
Imports Sys = System
Imports Tex = System.Text
Imports Xsd = System.Xml.Schema
Imports W3c = System.Xml
Imports Val = Enhancements.Basic.Expressions.Values
Imports Vbn = Microsoft.VisualBasic

Namespace Enhancements.Basic.Expressions
    ''' <summary>Represents a token extracted from an expression that has a variable's name.</summary>
    ''' <remarks>A variable name must start with the prefix specified by the PrefixRepresentation property.</remarks>
    <Serializable(), DebuggerStepThrough()> _
    Public NotInheritable Class Variable
        Inherits Token

        Private Sub New(ByVal _expression As System.String, ByVal _expressionBeginIndex As Sys.Int32, ByVal _expressionEndIndex As Sys.Int32)
            MyBase.New(_expression, _expressionBeginIndex, _expressionEndIndex)
        End Sub

        ''' <summary>The prefix that these tokens representations must begin with.</summary>
        Public Shared ReadOnly Property PrefixRepresentation() As System.String
            Get
                Dim _returnValue As System.String = ___Texts.ToUpper("$")

                Return _returnValue
            End Get
        End Property

        Private Shared Function __Parse(ByVal _expression As System.String, ByVal _expressionBeginIndex As Sys.Int32) As Sys.Object
            Dim _returnValue As Sys.Object = Nothing
            If _expression.IsNullNot("_expression", False) AndAlso _expression.IsEmptyNot("_expression", False) AndAlso _expressionBeginIndex.IsInRange("_expressionBeginIndex", 0, _expression.Length - 1, False) Then
                If ___Texts.StartsWith(_expression.Substring(_expressionBeginIndex), PrefixRepresentation) Then
                    Dim _returnValueString As System.String = Nothing
                    For _counter As Sys.Int32 = _expression.Length - 1 To _expressionBeginIndex + PrefixRepresentation.Length Step -1
                        Dim _dummy As System.String = _expression.Substring(_expressionBeginIndex + PrefixRepresentation.Length, _counter - _expressionBeginIndex - PrefixRepresentation.Length + 1)
                        If ___Identifiers.AssertIsValid(_dummy, False) Then
                            _returnValueString = PrefixRepresentation + _dummy
                            Exit For
                        End If
                    Next _counter
                    If _returnValueString.IsNullNot("_returnValueString", False) Then
                        _returnValue = New Variable(_expression, _expressionBeginIndex, _expressionBeginIndex + _returnValueString.Length - 1)
                    End If
                End If
            End If
            If Assert.IsNull(_returnValue, "_returnValue", False) Then
                _returnValue = VariableParseException.___Create(_expression, _expressionBeginIndex)
            End If

            Return _returnValue
        End Function

        ''' <summary>Parses an expression for a variable's name starting by a begin index.</summary>
        ''' <param name="_expression">Expression to parse.</param>
        ''' <param name="_expressionBeginIndex">Expression begin index to use.</param>
        ''' <exception cref="VariableParseException">The operation did not produce a valid token.</exception>
        ''' <returns> </returns>
        Public Overloads Shared Function Parse(ByVal _expression As System.String, ByVal _expressionBeginIndex As Sys.Int32) As Variable
            Dim _returnValue As Sys.Object = __Parse(_expression, _expressionBeginIndex)
            If Assert.IsOfType(_returnValue, "_returnValue", GetType(VariableParseException), False) Then
                VariableParseException.___Throw(CType(_returnValue, VariableParseException))
            End If

            Return CType(_returnValue, Variable)
        End Function

        ''' <summary>Tries to parse an expression for a variable's name starting by a begin index.</summary>
        ''' <param name="_expression">Expression to parse.</param>
        ''' <param name="_expressionBeginIndex">Expression begin index to use.</param>
        ''' <param name="_result">The result of the operation if possible. If not, null is returned.</param>
        ''' <returns> </returns>
        Public Overloads Shared Function TryParse(ByVal _expression As System.String, ByVal _expressionBeginIndex As Sys.Int32, ByRef _result As Variable) As System.Boolean
            Dim _returnValue As System.Boolean = False
            Dim _dummy As Sys.Object = __Parse(_expression, _expressionBeginIndex)
            If Assert.IsOfType(_dummy, "_dummy", GetType(VariableParseException), False) Then
                _result = Nothing
                _returnValue = False
            Else
                _result = CType(_dummy, Variable)
                _returnValue = True
            End If

            Return _returnValue
        End Function

        ''' <summary>Determines the token's correct representation for use in an expression.</summary>
        ''' <returns> </returns>
        Public Overrides Function ToRepresentation() As System.String
            Dim _returnValue As System.String = ___Texts.ToUpper(ExpressionPart)

            Return _returnValue
        End Function

        Private __Type As Sys.Type = Nothing
        ''' <summary>The variable's type.</summary>
        ''' <remarks>It can be defined only once.</remarks>
        ''' <exception cref="IsNullNotException">Type is not null.</exception>
        ''' <exception cref="IsNullException">_value is null.</exception>
        ''' <exception cref="IsTrueNotException">_value represents an invalid type for a variable.</exception>
        Public Property Type() As Sys.Type
            Get
                Return __Type
            End Get
            Friend Set(ByVal _value As Sys.Type)
                Type.IsNull("Type", True)
                _value.IsNullNot("Type._value", True)
                Val.Value.___AssertIsValidType(_value).IsTrue("Val.Value.___AssertIsValidType(_value)", True)

                __Type = _value
            End Set
        End Property

        ''' <exception cref="IsNullException"> </exception>
        ''' <exception cref="IsListFilledNotException"> </exception>
        Friend Shared Function ___ParseAll(ByRef _tokens As Gen.List(Of Token)) As Sys.Int32
            _tokens.IsListFilled("_tokens", True)

            Dim _returnValue As Sys.Int32 = 0
            Dim _tokensNew As Gen.List(Of Token) = New Gen.List(Of Token)()
            For _counter1 As Sys.Int32 = 0 To _tokens.Count - 1
                If _tokens(_counter1).IsOfType("_tokens(_counter1)", GetType(Undetermined), False) Then
                    Dim _tokensToken As Undetermined = CType(_tokens(_counter1), Undetermined)
                    For _counter2 As Sys.Int32 = 0 To _tokensToken.ExpressionPart.Length - 1
                        Dim _variable As Variable = Nothing
                        If TryParse(_tokensToken.Expression, _tokensToken.ExpressionBeginIndex + _counter2, _variable) Then
                            _tokensNew.Add(_variable)
                            _counter2 += _variable.ExpressionPart.Length - 1
                            _returnValue += 1
                        Else
                            Undetermined.___AppendNewToEndOrReplaceLastWithNew(_tokensNew, _tokensToken.Expression, _tokensToken.ExpressionBeginIndex + _counter2, _tokensToken.ExpressionBeginIndex + _counter2)
                        End If
                    Next _counter2
                Else
                    _tokensNew.Add(_tokens(_counter1))
                End If
            Next _counter1
            _tokens = _tokensNew

            Return _returnValue
        End Function

        ''' <exception cref="IsNullException"> </exception>
        ''' <exception cref="IsListFilledNotException"> </exception>
        Friend Shared Function ___GetDistinct(ByVal _tokens As Gen.List(Of Token)) As Variable()
            _tokens.IsListFilled("_tokens", True)

            Dim _returnValueList As Gen.List(Of Variable) = New Gen.List(Of Variable)()
            For Each _token As Token In _tokens
                If _token.IsOfType("_token", GetType(Variable), False) Then
                    Dim _variableIsInReturnValueList As System.Boolean = False
                    For _counter As Sys.Int32 = 0 To _returnValueList.Count - 1
                        If ___Texts.AreEqual(_returnValueList(_counter).ExpressionPart, _token.ExpressionPart) Then
                            _variableIsInReturnValueList = True
                            Exit For
                        End If
                    Next _counter
                    If _variableIsInReturnValueList.IsTrueNot("_variableIsInReturnValueList", False) Then
                        _returnValueList.Add(CType(_token, Variable))
                    End If
                End If
            Next _token

            Return _returnValueList.ToArray()
        End Function

        Friend Shared Function ___NamesReferToTheSameVariable(ByVal _firstName As System.String, ByVal _secondName As System.String) As System.Boolean
            Dim _returnValue As System.Boolean = ___Texts.AreEqual(_firstName, _secondName)

            Return _returnValue
        End Function

    End Class
End Namespace
